<?php
/**
 * Created by PhpStorm.
 * User: Aliaksei Lazerka
 * Date: 9/28/14
 * Time: 3:09 PM
 */

namespace log;

use files\FileUtils;

if (!defined('NYMPH_ROOT')) {
  define('NYMPH_ROOT', dirname("../../../" . __FILE__));
  require(NYMPH_ROOT . '/local/loader/kernel/classes/URLClassLoader.php');
}

class FileLogger extends Logger
{

  private $fileUtils;

  function __construct()
  {
    $this->fileUtils = new FileUtils();
  }

  /**
   * (PHP 5)<br/>
   * info level
   * @param string $message
   */
  function info($message)
  {
    $out = "[" . Logger::INFO_LEVEL . "] " . $this->convertForLog($message) . "\n";
    $this->writeToFile($out);
  }

  /**
   * (PHP 5)<br/>
   * error level
   * @param string $message
   */
  function debug($message)
  {
    $out = "[" . Logger::DEBUG_LEVEL . "] " . $this->convertForLog($message) . "\n";
    $this->writeToFile($out);
  }

  /**
   * (PHP 5)<br/>
   * debug level
   * @param string $message
   */
  function error($message)
  {
    $out = "[" . Logger::ERROR_LEVEL . "] " . $this->convertForLog($message) . "\n";
    $this->writeToFile($out);
  }

  function writeToFile($object)
  {
    $allowOutput = false;
    $caller = next(debug_backtrace())['function'];
    switch (strtoupper($caller)) {
      case (self::INFO_LEVEL):
        $allowOutput = true;
        break;
      case (self::ERROR_LEVEL):
        if (self::INT_ERROR_LEVEL >= $this->getLogLevelAsInt()) {
          $allowOutput = true;
        }
        break;
      case (self::DEBUG_LEVEL):
        if (self::INT_DEBUG_LEVEL >= $this->getLogLevelAsInt()) {
          $allowOutput = true;
        }
        break;
    }
    if ($allowOutput) {
      if ($this->getLogConfig()->isAppend()) {
        $this->fileUtils->writeToFile($this->getLogConfig()->getPathToFile(), $object);
      } else {
        $this->fileUtils->writeToFile($this->getLogConfig()->getPathToFile(), $object, true);
      }
    }
  }
}